package xyz.xtt.schedule.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.common.starter.cache.GlobalTableCache;
import xyz.xtt.schedule.entity.AssetExtEntity;
import xyz.xtt.schedule.mapper.asset.AssetExtMapper;

@Service
public class AssetExtService extends ServiceImpl<AssetExtMapper, AssetExtEntity> {
	@Autowired
	private CacheManager cacheManager;

	public void updateAssetChainByAssetId(String assetId, String hash, String blockNum, int createDateTime) {
		UpdateWrapper<AssetExtEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper
				.eq("asset_id", assetId)
				.set("token_id", assetId)
				.set("chain_name", "武汉链")
				.set("chain_id", 5555)
				.set("chain_block_num", blockNum)
				.set("chain_tx_hash", hash)
				.set("chain_time", createDateTime);
		int update = baseMapper.update(updateWrapper);
		if (update > 0) {
			// 清除缓存
			cacheManager.delete(GlobalTableCache.TBL_ASSET_EXT, assetId);
		}
	}

	public AssetExtEntity findByAssetId(String assetId) {
		QueryWrapper<AssetExtEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("asset_id", assetId);
		return baseMapper.selectOne(queryWrapper);
	}

	/**
	 * 查询符合要铸造的数字资产列表
	 */
	public List<AssetExtEntity> findMintList() {
		QueryWrapper<AssetExtEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.gt("token_id", 0);
		queryWrapper.isNotNull("metadata");
		queryWrapper.eq("up_chain", 1);
		queryWrapper.and(wrapper -> wrapper.eq("chain_tx_hash", "").or().isNull("chain_tx_hash"));
		return list(queryWrapper);
	}

	/**
	 * 查询符合要更新链交易信息列表
	 */
	public List<AssetExtEntity> findUpdateChainInfoList() {
		QueryWrapper<AssetExtEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.isNotNull("chain_tx_hash");
		queryWrapper.isNull("chain_block_num");
		return list(queryWrapper);
	}

	public void updateHashByTokenId(String tokenId, String hash) {
		UpdateWrapper<AssetExtEntity> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("token_id", tokenId).set("chain_tx_hash", hash);
		baseMapper.update(updateWrapper);
	}
}
